package streaming.flume

import org.apache.spark.SparkConf
import org.apache.spark.streaming.flume.FlumeUtils
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
  * 从flume中读取数据进行统计（push方式）
  * 先启动spark，再启动pull
  * 注意：spark-submit --packages org.apache.spark:spark-streaming-flume_2.11:2.3.2
  * 运行的时候会自动帮你下载依赖,也可使用下载jar包后使用--jars 包含进来
  */
object FlumePushWordCount {

  def main(args: Array[String]): Unit = {

    if (args.length != 2) {
      System.err.println("Usage: FlumePushWordCount <hostname> <port>")
      System.exit(1)
    }

    val Array(hostname, port) = args

    val sc = new SparkConf().setMaster("local[*]").setAppName("FlumePushWordCount")
    val ssc = new StreamingContext(sc,Seconds(5))

    val flumeStream = FlumeUtils.createStream(ssc,hostname,port.toInt)

    flumeStream.map(x=>new String(x.event.getBody.array()).trim)
      .flatMap(_.split(" ")).map((_,1)).reduceByKey(_+_).print()

    ssc.start()
  }
}
